var network_user = {
	http : Ti.Network.createHTTPClient({
		validatesSecureCertificate:false,
		timeout:Ti.App.config.connection_timeout,
		useSessionPersistence : false,
		useKeychainPersistence : false,
		shouldUseRFC2616RedirectBehaviour : false,
		shouldRedirect : false,
		useCookiePersistence :false
	}),
	
	showAlert : function(titol,text){
		var alertDialog = Titanium.UI.createAlertDialog({
			title: titol,
			message: text,
			buttonNames: ['OK']
	    });
		alertDialog.show();
	},
	
	checkNetworkAvailability : function (showAlert){
		if((showAlert == null || showAlert == true) && Ti.Network.networkType == Ti.Network.NETWORK_NONE){
			this.showAlert(L('WARNING'),L('Your device is not online.'));
		    return false;
		}
		return true;
	},
	
	getCookieValue : function (getCookieValue_str){
		var getCookieValue_cookie = getCookieValue_str.substr(-104,69);
		var getCookieValue_array = getCookieValue_cookie.split("=");
		var cookie_string = null;
		if(getCookieValue_array.length == 2 && getCookieValue_array[0].length==36 && getCookieValue_array[1].length == 32){
			cookie_string = getCookieValue_cookie;
		}else{
			cookie_string = '';
		}
		Ti.API.info("contenido de cookie:" + cookie_string);
		return cookie_string;
	},

	getTokenFromWeb : function(user,password){
		Ti.API.info("network_user.getTokenFromWeb()");	
		
		if (this.checkNetworkAvailability()){
			var cookieStr = null;
			var url = Ti.App.config.url_ideatorrent +"?destination=ideatorrent";
			
			var post_data = {
				"name":user,
				"pass":password,
				"op":'Entra',
				'form_id':'user_login_block'
			};
			
			this.http.open('POST',url);
			this.http.setRequestHeader('referer',url);
			this.http.setRequestHeader('User-Agent',Ti.App.config.user_agent);
			
			this.http.onerror = function(e){ 
				Ti.App.fireEvent('tokenDownloadKo',{error:'connection error',errorStr: e.error});
			};
			
			this.http.onload = function(){
				 Ti.API.info("Loaded! Status: " + this.status);
				if (this.status == 302){
					cookieStr = this.getResponseHeader("Set-Cookie");
					var cookieObj = network_user.getCookieValue(cookieStr);
					Ti.App.fireEvent('tokenDownloadOk',{token:cookieObj});
				}else{
					if (this.responseText.search("Ho sentim, el nom d'usuari o la contrasenya no s") != -1){
						Ti.App.fireEvent('tokenDownloadKo',{error:'invalid user'});
					}else{
						Ti.App.fireEvent('tokenDownloadKo',{error:'unknown error'});
					}
					//if (this.responseText.search("Ho sentim, el nom d'usuari o la contrasenya no s") != -1){
				}
			};
			
			// send the data
			this.http.send(post_data);
		}
	},
	
	checkToken : function(){
		Ti.API.info("network_user.checkToken()");	
		var token = Ti.App.user.getToken();
		if(this.checkNetworkAvailability() && token != ''){
			var url_get = Ti.App.config.url_profile;
			this.http.open('GET',url_get);
			
			this.http.setRequestHeader('User-Agent',Ti.App.config.user_agent);
			this.http.setRequestHeader('referer',url_get);
			this.http.setRequestHeader("Cookie", token);
			
			this.http.onerror = function(e){Ti.API.info("ERROR " + e.error);};
			
			this.http.onload = function()
			{
				//Ho sentim, el nom d'usuari o la contrasenya no s
				if(this.status == 200 && this.responseText.search("Aquest és el vostre id d'usuari") != -1){
					Ti.API.info("RESULTADO OK");
					alert("RESULTADO OK");
				}else{
					Ti.API.info("RESULTADO KO");
					alert("RESULTADO KO");
				}
				
			};
			
			this.http.send();
		}
	},
	
	vote : function(solucioId,vot){
		Ti.API.info("network_user.vote("+ solucioId +"," + vot +")");
		var token = Ti.App.user.getToken();
		if(this.checkNetworkAvailability() && token != ''){
			var url_get = Ti.App.config.url_vot +solucioId +"/"+vot;
			Ti.API.info("network_user.vote()"+ url_get);
			
			this.http.open('GET',url_get);
			
			this.http.setRequestHeader("Cookie", token);
			this.http.setRequestHeader('referer',url_get);
			this.http.setRequestHeader('User-Agent',Ti.App.config.user_agent);
			
			this.http.onerror = function(e){
				Ti.API.info("vote error " + e.error);
				Ti.App.fireEvent('voteKo');
			};
			this.http.onload = function(){
				if(this.status == 200){
					if (this.responseText == "AJAXOK"){
						Ti.API.info("network_user.vote() -> OK");
						Ti.App.fireEvent('voteOk');
					}else if(this.responseText == "AJAXERROR"){
						Ti.API.info("network_user.vote() -> KO");
						Ti.App.fireEvent('voteKo');
					}
				}else{
					Ti.API.info("network_user.vote() -> KO");
					Ti.App.fireEvent('voteKo');
				}
			};
			
			this.http.send();
		}else{
			Ti.API.info("network_user.vote() token empty!");
			
		}
	},
	
	addComment : function(ideaId,text){
		Ti.API.info("network_user.comment("+ ideaId +"," + text +")");
		var token = Ti.App.user.getToken();
		if(this.checkNetworkAvailability() && token != ''){
			var url_get = Ti.App.config.url_comentari +ideaId;
			Ti.API.info("network_user.addComment()"+ url_get);
			var post_data = {
				commennt_text:text,
				_comment_submitted : true
			};
			
			this.http.open('GET',url_get);
			
			this.http.setRequestHeader("Cookie", token);
			this.http.setRequestHeader('referer',url_get);
			this.http.setRequestHeader('User-Agent',Ti.App.config.user_agent);
			
			this.http.onerror = function(e){
				Ti.API.info("comment error " + e.error);
				Ti.App.fireEvent('addCommentKo');
			};
			this.http.onload = function(){
				if(this.status == 302){
					Ti.App.fireEvent('addCommentOk');
				}else{
					Ti.API.info("network_user.comment() -> KO");
					Ti.App.fireEvent('addCommentKo');
				}
			};
			
			this.http.send(post_data);
		}else{
			Ti.API.info("network_user.addComment() token empty!");
			
		}
	},
	
	getVotesFromIdea : function(idea){
		Ti.API.info("network_user.getVotesFromIdea("+ idea +")");
		var token = Ti.App.user.getToken();
		if(this.checkNetworkAvailability(false) && token != ''){
			var url_get = Ti.App.config.url_idea + idea;
			Ti.API.info("network_user.getVotesFromIdea()"+ url_get);
			
			this.http.open('GET',url_get);
			
			this.http.setRequestHeader("Cookie", token);
			this.http.setRequestHeader('referer',url_get);
			this.http.setRequestHeader('User-Agent',Ti.App.config.user_agent);
			
			this.http.onerror = function(e){
				Ti.API.info("getVotesFromIdeaKo " + e.error);
				Ti.App.fireEvent('getVotesFromIdeaKo');
			};
			this.http.onload = function(){
				if(this.status == 200){
					var vots = [];
					var exp =/\b(img src=".*title="Heu.*" id="votingimage(up|down|equal)-[0-9]{1,})"/mig;
					var hits = this.responseText.match(exp);
					var hitTmp = "";
					var hitSituacioTmp = "";
					if (hits) {
						for (var i in hits){
							if (!isNaN(i)){
								hitTmp = hits[i].split('id="votingimage');
								var expUpDownEq =/(up|down|equal)/ig;
								var hitSituacio = hitTmp[1].match(expUpDownEq);
								var expSolucio =/[0-9]{1,}/ig;
								var hitSolucio = hitTmp[1].match(expSolucio);
								//Ti.API.info("hitIdea, hitSituacio " +hitIdea + " "+ hitSituacio);
								if(hitSituacio =="up"){
									hitSituacioTmp = "1";
								}else if(hitSituacio == "down"){
									hitSituacioTmp = "-1";
								}else if(hitSituacio == "equal"){
									hitSituacioTmp = "0";
								}
								vots.push({solucio:hitSolucio,vot:hitSituacioTmp});
								//Ti.App.db.votarSolucio(hitSolucio,hitSituacioTmp);
							}
						}
						Ti.API.info("vots trobats:"+vots);
					}else{
						Ti.API.info("vots no trobat text");
					}
					
					Ti.App.fireEvent('getVotesFromIdeaOk',{vots:vots});
				}else{
					Ti.API.info("network_user.vote() -> KO");
					Ti.App.fireEvent('getVotesFromIdeaKo');
				}
			};
			
			this.http.send();
		}else{
			Ti.API.info("network_user.vote() token empty!");
		}
	}
};
